from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Query
from pydantic import BaseModel
from apps.models import Coach, User, User_Profiles, Training_Programs, Training_Categories, Student, Student_trainings
from tortoise.transactions import in_transaction
programs = APIRouter()

class ProgramProfileResponse(BaseModel):
    program_id: int
    name: str
    description: Optional[str]
    category_id: int  # 来自 Training_Categories 表

    class Config:
        orm_mode = True

class ProgramCreateRequest(BaseModel):
    name: str
    description: Optional[str]
    category_id: int  # 来自 Training_Categories 表
    create_by_id: int  # 添加 create_by_id 参数

class ProgramUpdateRequest(BaseModel):
    name: str
    description: Optional[str]
    category_id: int  # 来自 Training_Categories 表

@programs.get("/msg")
async def get_all_programs(page: int = Query(1, ge=1), page_size: int = Query(10, ge=1, le=100)):
    # 计算偏移量
    offset = (page - 1) * page_size
    # 获取总数
    total = await Training_Programs.filter(is_active=True).count()
    # 查询当前页的课程数据
    programs = await Training_Programs.filter(is_active=True).offset(offset).limit(page_size).values(
        "program_id",
        "name",
        "description",
        category_id="category_id_id"  # 外键字段名是 category_id_id
    )

    return {
        "status": 200,
        "message": "success",
        "data": programs,
        "total": total
    }
@programs.get("/byStuId/msg/{student_id}")
async def get_student_programs_count(student_id: int):
    """
    通过学生ID获取该学生所有学习的科目数量
    """
    try:
        # 检查学生是否存在
        student = await Student.get_or_none(student_id=student_id)
        if not student:
            return {
                "status": 404,
                "message": "Student not found",
                "data": 0
            }

        # 查询该学生所有学习的科目数量
        programs_count = await Student_trainings.filter(student_id=student_id).count()

        return {
            "status": 200,
            "message": "success",
            "data": programs_count
        }

    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving student programs count: {str(e)}",
            "data": 0
        }



@programs.post("/add")
async def create_category(data: ProgramCreateRequest):
    # 检查类名是否存在
    existing_program = await Training_Programs.get_or_none(name=data.name)
    if existing_program:
        return {"status": 400, "message": "Program name already exists"}

    try:
        # 获取当前用户
        current_user = await User.get_or_none(user_id=data.create_by_id)
        if not current_user:
            return {"status": 404, "message": "User not found"}
        # 获取 category 实例
        category = await Training_Categories.get_or_none(category_id=data.category_id)
        if not category:
            return {"status": 404, "message": "Category not found"}

        async with in_transaction() as connection:
            program = await Training_Programs.create(
                name=data.name,
                description=data.description,
                create_by=current_user,  # 传入 User 实例，不是 user_id
                category_id=category,
                using_db=connection
            )

        return {
            "status": 201,
            "message": "Program created successfully",
            "data": {
                "program_id": program.program_id,
                "name": program.name,
                "description": program.description,
                "category_id": program.category_id_id,
                "create_by_id": program.create_by_id  # 返回创建者ID
            }
        }

    except Exception as e:
        return {"status": 500, "message": f"Error creating program: {str(e)}"}

@programs.put("/update/{program_id}")
async def update_coach(program_id: int, data: ProgramUpdateRequest):
    # 查询 Program
    program = await Training_Programs.get_or_none(program_id=program_id)
    if not program:
        return {"status": 404, "message": "Program not found"}

    update_data = data.dict(exclude_unset=True)  # 只获取提供的字段
    # 更新 Program 表
    if any(k in update_data for k in ['name','description', 'category_id']):
        await program.update_from_dict({
            k: v for k, v in update_data.items()
            if k in ['name','description']
        })
    # 更新 category_id（如果提供了）
    if 'category_id' in update_data:
        category = await Training_Categories.get_or_none(category_id=update_data['category_id'])
        if not category:
            return {"status": 404, "message": "Category not found"}
        program.category_id = category  # 或者使用 program.category_id_id = update_data['category_id']
    await program.save()

    return {"status": 200, "message": "Program updated successfully"}

@programs.delete("/delete/{program_id}")
async def delete_program(program_id: int):
    program = await Training_Programs.get_or_none(program_id=program_id)
    if not program:
        return {"status": 404, "message": "Program not found"}
    await program.delete()
    return {"status": 200, "message": "Program deleted successfully"}